package xyz.yuanjilu.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import xyz.yuanjilu.base.AbstractPageProcessor;
import xyz.yuanjilu.base.AntAction;
import xyz.yuanjilu.base.AntInfo;
import xyz.yuanjilu.entity.AntWebSiteEntity;
import xyz.yuanjilu.entity.ScheduleJobEntity;
import xyz.yuanjilu.service.AntWebSiteService;
import xyz.yuanjilu.service.ScheduleJobService;
import xyz.yuanjilu.service.WebAntManagerService;
import xyz.yuanjilu.utils.Constant.ScheduleStatus;
import xyz.yuanjilu.utils.ScheduleUtils;

@Service
public class WebAntManagerImpl implements WebAntManagerService {
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    Map<String, AntAction> antActionMap;
    
    @Autowired
    private AntWebSiteService antWebSiteService;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Override
    public AntInfo queryObject(String id) {
        AntAction antAction = antActionMap.get(id);
        AntInfo antInfo=new AntInfo();
        antInfo.setId(id);
        antInfo.setStatus(antAction.status());
        antInfo.setName(antAction.getClass().getName());
        return antInfo;
    }

    @Override
    public List<AntInfo> queryList(Map<String, Object> map) {
        List<AntInfo> AntInfos=new ArrayList<AntInfo>();
        for(Entry<String, AntAction> entry: antActionMap.entrySet()) { 
            AntAction antAction = entry.getValue();
            String id = entry.getKey();
            AntInfo antInfo=new AntInfo();
            antInfo.setId(id);
            antInfo.setStatus(antAction.status());
            antInfo.setName(antAction.getClass().getName());
            antInfo.setRemarks(antAction.remarks());
            antInfo.setWebSite(antWebSiteService.getWebSiteEntity(id));
            antInfo.setWetSiteName(antInfo.getWebSite()==null?"":antInfo.getWebSite().getWebName());
            if (antAction instanceof AbstractPageProcessor) {
				AbstractPageProcessor abstractPageProcessor = (AbstractPageProcessor) antAction;
				antInfo.setInitTargetUrl(abstractPageProcessor.initTargetUrl());
			}
            Map param=new HashMap();
			param.put("beanNameTarget", id);
			List<ScheduleJobEntity> queryList = scheduleJobService.queryList(param);
			if (CollectionUtils.isNotEmpty(queryList)) {
				ScheduleJobEntity scheduleJobEntity = queryList.get(0);
				antInfo.setScheduleJobStatus(scheduleJobEntity.getStatus()+"");
				antInfo.setScheduleJobNextRunTime(ScheduleUtils.getNextRunTime(scheduleJobEntity.getCronExpression()).get(0));
			}
            AntInfos.add(antInfo);
        }
        return AntInfos;
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        
        return antActionMap.size();
    }

    @Override
    public void start(String id) {
        AntAction antAction = antActionMap.get(id);
        antAction.start();
        
    }

    @Override
    public void restart(String id) {
        AntAction antAction = antActionMap.get(id);        
        antAction.restart();
    }

    @Override
    public void stop(String id) {
        AntAction antAction = antActionMap.get(id);         
        antAction.stop();
    }

    @Override
    public void start(String[] ids) {
      for (String id : ids) {
        this.start(id);
      }
    }

    @Override
    public void restart(String[] ids) {
        for (String id : ids) {
            this.restart(id);
          }
    }

    @Override
    public void stop(String[] ids) {
        for (String id : ids) {
            this.stop(id);
       }
    }

    @Override
    public void bindwebsite(String[] ids, String selectWebId) {
        antWebSiteService.deleteBatchByAntBeanIds(ids);
        for (int i = 0; i < ids.length; i++) {
            AntWebSiteEntity antWebSiteEntity=new AntWebSiteEntity();
            antWebSiteEntity.setAntBeanId(ids[i]);
            antWebSiteEntity.setWebSiteId(selectWebId);
            antWebSiteService.save(antWebSiteEntity);
        }
    }

	@Override
	public void addScheduleJob(String[] ids) {
		for (String beanId : ids) {
			Map param=new HashMap();
			param.put("beanNameTarget", beanId);
			List<ScheduleJobEntity> queryList = scheduleJobService.queryList(param);
			if (CollectionUtils.isEmpty(queryList)) {
				ScheduleJobEntity scheduleJobEntity=new ScheduleJobEntity();
				scheduleJobEntity.setBeanName(beanId);
				scheduleJobEntity.setMethodName("start");
				scheduleJobEntity.setCronExpression("0 0 0/1 * * ?");
				scheduleJobEntity.setStatus(ScheduleStatus.PAUSE.getValue());
				scheduleJobService.save(scheduleJobEntity);
			}
		}
		
	}
	@Override
	public void startScheduleJob(String[] ids) {
		List<Long> jobIds=new ArrayList<Long>();
		Long[] jobIdstem = {};
		for (String beanId : ids) {
			Map param=new HashMap();
			param.put("beanNameTarget", beanId);
			List<ScheduleJobEntity> queryList = scheduleJobService.queryList(param);
			if (CollectionUtils.isNotEmpty(queryList)) {
				ScheduleJobEntity scheduleJobEntity=queryList.get(0);
				jobIds.add(scheduleJobEntity.getJobId());
			}
		}
		scheduleJobService.resume(jobIds.toArray(jobIdstem));
		
	}
	@Override
	public void stopScheduleJob(String[] ids) {
		List<Long> jobIds=new ArrayList<Long>();
		Long[] jobIdstem = {};
		for (String beanId : ids) {
			Map param=new HashMap();
			param.put("beanNameTarget", beanId);
			List<ScheduleJobEntity> queryList = scheduleJobService.queryList(param);
			if (CollectionUtils.isNotEmpty(queryList)) {
				ScheduleJobEntity scheduleJobEntity=queryList.get(0);
				jobIds.add(scheduleJobEntity.getJobId());
			}
		}
		scheduleJobService.pause(jobIds.toArray(jobIdstem));
	}
    
}
